package sz.com.postoffice.jxyzwgcase.service.impl;

import static com.github.drinkjava2.jdbpro.JDBPRO.noNull;
import static com.github.drinkjava2.jdbpro.JDBPRO.sql;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.drinkjava2.jsqlbox.DbContext;
import com.huawei.ucmarket.security.permission.tool.CommonHelper;
import com.huawei.ucmarket.security.permission.vo.UserInfo;

import lombok.extern.slf4j.Slf4j;
import sz.com.postoffice.jxyzwgcase.dao.master.SalesDepartmentDao;
import sz.com.postoffice.jxyzwgcase.pojo.SalesDepartment;
import sz.com.postoffice.jxyzwgcase.service.UserService;
import sz.com.postoffice.jxyzwgcase.utils.HttpsUtil;

/**
 * @ClassName UserServiceImpl
 * @Deacription TODO
 * @Author 王盟
 * @Date 2020/10/23 15:38
 * @Version 1.0
 **/

@Service
@Slf4j
@EnableScheduling
public class UserServiceImpl implements UserService {

    @Value("${ADO.get_token_url}")
    private String getTokenUrl;
    @Value("${ADO.user_name}")
    private String userName;
    @Value("${ADO.password}")
    private String password;
    @Value("${ADO.user_url}")
    private String userUrl;
    @Value("${ADO.tenantId}")
    private String tenantId;

    @Value("${ADO.roleId}")
    private String roleId;

    @Resource
    private SalesDepartmentDao salesDepartmentDao;

    @Override
    public UserInfo getUserInfo() {

        UserInfo info = CommonHelper.getCurrentUser();

        return info;
    }

    @Override
    public List<SalesDepartment> getSalesList() {
        return salesDepartmentDao.findAll();
    }

    @Override
    public String getADOToken(JSONObject jsonObject) {

        if (null == jsonObject || jsonObject.size() == 0) {
            jsonObject = new JSONObject();
            jsonObject.put("userName", userName);
            jsonObject.put("password", password);
        }
        // 这里获取token，将token参数传空，将jsonObject字符串传入
        return HttpsUtil.post(getTokenUrl, jsonObject.toJSONString(), null);
    }

    @Scheduled(fixedDelay = 3600000)
    public void getUser() {
        getUserList(null);
    }

    // 定时获取用户信息
    public void getUserList(String empCode) {
        DbContext dbContext = DbContext.getGlobalDbContext();
        String queryEmpCodeSql;
        if (StringUtils.isNotBlank(empCode)) {
            queryEmpCodeSql = "select "
                    + "`id`,`grid_code`, `emp_code`, `emp_dept_code`, `emp_dept_name`, `emp_section_code`, `emp_section_name`,"
                    + " `ado_id` from dwr_jxyz_emp_d where emp_code = '" + empCode + "'";
        } else {
            queryEmpCodeSql = "select "
                    + "`id`,`grid_code`, `emp_code`, `emp_dept_code`, `emp_dept_name`, `emp_section_code`, `emp_section_name`,"
                    + " `ado_id` from dwr_jxyz_emp_d where emp_code is not null and emp_code != '';";
        }

        List<Map<String, Object>> userList = dbContext.iQueryForMapList(queryEmpCodeSql);
        log.debug("wait user init size:{}", userList.size());
        String token = getADOToken(null);
        // 拼装url
        String key = "?tenantId=" + tenantId;
        JSONArray results = JSONObject.parseObject(HttpsUtil.get(token, userUrl + key)).getJSONArray("result");
        for (Map<String, Object> userMap : userList) {
            empCode = (String) userMap.get("emp_code");
            empCode = empCode.trim();
            Long id = (Long) userMap.get("id");
            String adoId;
            String empSectionCode = null;
            String empSectionName = null;
            String empDeptCode = null;
            String empDeptName = null;

            if (results.size() > 0) {
                for (Object result : results) {
                    JSONObject user = JSONObject.parseObject(result.toString());
                    String userCode = user.getString("userName");
                    if (empCode.equals(userCode)) {
                    	JSONArray assignContents = user.getJSONArray("assignContent");
                        JSONArray roleList = new JSONArray();
                        adoId = JSONObject.parseObject(result.toString()).getString("userId");
                        JSONObject roleObj = new JSONObject();
                        for (int i = 0; i < assignContents.size(); i++) {
                            JSONObject assign = assignContents.getJSONObject(i);
                            
                            JSONObject role = new JSONObject();
                            role.put("roleId", assign.getString("roleId"));
                            role.put("roleName", assign.getString("roleName"));
                            roleList.add(role);
                           
                            if (assign.getString("roleId").equals(roleId)) {// 段道级管理员
                                String secCode = assign.getString("roleTargetId");
                                // 查询段道
                                String sectionSql = " select  parent_code,name from t_grid_m where level = 5 ";
                                List<Map<String, Object>> empSectionMap = dbContext.iQueryForMapList(sectionSql,
                                        noNull(" and code = ?", secCode));
                                if (empSectionMap.size() > 0) {
                                    String secName = (String) empSectionMap.get(0).get("name");
                                    String deptCode = (String) empSectionMap.get(0).get("parent_code");
                                    // 查询部门
                                    String deptSql = " select  parent_code,name from t_grid_m where 1=1 ";
                                    List<Map<String, Object>> deptMap = dbContext.iQueryForMapList(deptSql,
                                            noNull(" and code = ?", deptCode));
                                    if (deptMap.size() > 0) {
                                        empSectionCode = secCode;
                                        empSectionName = secName;
                                        empDeptCode = deptCode;
                                        empDeptName = (String) deptMap.get(0).get("name");
                                        break;
                                    }
                                }
                            }
                        }
                        roleObj.put("roles", roleList);
                        // 更新
                        try {
                        	dbContext.iExecute("UPDATE dwr_jxyz_emp_d ",
                    				noNull(" SET ado_id = ?", adoId), 
                    				noNull(",emp_dept_name = ?", empDeptName),
                    				noNull(",emp_section_code = ?", empSectionCode),
                    				noNull(",grid_code = ?", empSectionCode),
                    				noNull(",emp_section_name = ?", empSectionName),
                    				noNull(",emp_dept_code = ?", empDeptCode),
                    				noNull(",`extend_column` = ?", roleObj.toString()),
                    				sql(" where id = " + id));
                        } catch (Exception e) {
                            log.error("修改异常==>{}", e.getMessage());
                            e.printStackTrace();
                        }
                        break;
                    }
                }
            }
        }
    }
    
}
